package ldh.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeUtil {

	public static Date toDate(String time, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format); 
        try {
			return sdf.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        return null;
	}
	
	public static String format(Date date, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format); 
        String c = sdf.format(date);
        return c;
	}
	
	public static String now(String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format); 
        String c = sdf.format(new Date());
        return c;
	}
	
	public static String previous(Date date, int previousTimeMill, String format) {
		long now = date.getTime();
		now -= previousTimeMill;
		Date d = new Date(now);
		return format(d, format);
	}
	
	public static String previous(Date date, long previousTimeMill, String format) {
		long now = date.getTime();
		now -= previousTimeMill;
		Date d = new Date(now);
		return format(d, format);
	}
	
	public static String previousFromNow(int previousTimeMill, String format) {
		return previous(new Date(), previousTimeMill, format);
	}
	
	public static long differ(Date date1, Date oldDate) {
		if (date1.before(oldDate)) {
			throw new IllegalArgumentException("第一个时间应该晚于第二个参数");
		}
		long n1 = date1.getTime();
		long n2 = oldDate.getTime();
		return n1 - n2;
	}
	
	public static Date beforeMinute(Date date) {
		long time = date.getTime();
		time -= 1000 * 60;
		return new Date(time);
	}
	
	public static Date nextMinute(Date date) {
		long time = date.getTime();
		time += 1000 * 60;
		return new Date(time);
	}
	
	public static String getWeekFormNow() {
		return getWeek(new Date());
	}
	
	public static String getWeek(Date date) {
		Calendar c = Calendar.getInstance(); 
		c.setTime(date);
		int week = c.get(Calendar.WEEK_OF_YEAR);
		int year = c.get(Calendar.YEAR);
		return year + "" + week;
	}
	
	public static int getMonth(Date date) {
		Calendar c = Calendar.getInstance(); 
		c.setTime(date);
		return c.get(Calendar.MONTH);
	}
	
	public static void sleep(long time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			//e.printStackTrace();
		}
	}
	
	public static int getHour(Date date) {
		Calendar calendar =  Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.HOUR_OF_DAY);
	}
	
	public static void main(String[] args) {
		String t = "2013030511";
		Date d = TimeUtil.toDate(t, Constant.yyyyMMddHH);
		System.out.println(getHour(d));
	}
}
